package org.dragonnova.business.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dragonnova.business.model.User;
import org.dragonnova.business.model.User.Second;
import org.dragonnova.business.service.UserService;
import org.dragonnova.business.util.WeixinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.base.pub.util.Base64Util;
import com.base.pub.web.BaseController;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> userLogin(HttpServletResponse resp,HttpServletRequest request,
										 HttpSession session, String userName,String password) {
		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(userName)) {
			return packInfo(false, "请输入用户名或密码！登录");
		}
		User user = null;
		try {
			user = userService.findAdminByName(userName);
			if (user == null) {
				return packInfo(false, "用户不存在！登录");
			} else {
				if (user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
					user.setPassword("");
					setLoginUser(session, (User) user);
					String ip=request.getRemoteAddr();
					userService.updateAdminIP(Base64Util.getFromBase64(user.getId()),ip);
					return packData(user);
				} else {
					return packInfo(false, "密码错误！登录");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/updateUser")
	@ResponseBody
	public Map<String, Object> updateUser(HttpServletRequest request,HttpSession session, User user) throws Exception {
		User loginUser = getLoginUser(session);
		if (user == null) {
			return packInfo(false, "尚未登录，修改");
		}
		if (user.getPassword() == null) {
			return packInfo(false, "请输入密码，修改");
		}
		if (loginUser.getId() != user.getId() || loginUser.getGid() == 1) {
			user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
			user.setLogin_ip(request.getRemoteAddr());
			user.setNickname(user.getUsername());
			user.setLogin_count("0");
			try {
				boolean success = userService.updateAdmin(user);
				if (success) {
					User newUser = userService.findAdminByName(loginUser.getUsername());
					newUser.setPassword("");
					setLoginUser(session, newUser);
				}
				return packSaveInfo(success);
			} catch (Exception e) {
				e.printStackTrace();
				return warnException(e);
			}
		} else {
			return packInfo(false, "无权操作，修改");
		}

	}

	@RequestMapping("/findUser")
	@ResponseBody
	public Map<String, Object> findUser(HttpSession session, String id, String searchText) {
		try {
			if (id != null && id.length() > 0) {
				id = getUserId(session, true).toString();
			} else {
				id = Base64Util.getFromBase64(id);
			}
			return packData(userService.findUser(id, searchText));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/findWxAdmin")
	@ResponseBody
	public Map<String, Object> findWxAdmin(HttpSession session, String searchText) {
		try {
			if (getUserId(session, true) == -10) {
				return packData(userService.findWxAdmin(searchText));
			} else {
				return packInfo(false, "无权操作，查询");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/getLoginUser")
	@ResponseBody
	public Map<String, Object> getloginUser(HttpSession session) {
		User user = getLoginUser(session);
		if (user == null) {
			return packInfo(false, "尚未登录，查询");
		} else {
			return packData(user);
		}
	}

	@RequestMapping("/delUser")
	@ResponseBody
	public Map<String, Object> delUser(HttpSession session, @RequestParam(value = "id", required = true) Integer id) {
		if (getUserId(session, true) == -10) {
			try {
				boolean success = userService.delUser(id);
				return packDelInfo(success);
			} catch (Exception e) {
				e.printStackTrace();
				return warnException(e);
			}
		} else {
			return packInfo(false, "无权操作，删除");
		}
	}

	@RequestMapping("/addUser")
	@ResponseBody
	public Map<String, Object> addUser(HttpSession session, @Validated(Second.class) User user, BindingResult result) {
		if (result.hasErrors()) {
			return bindingResult(result);
		}
		if (getUserId(session, true) == -10) {
			try {
				user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
				if (user.getWxopenid() == null)
					user.setWxopenid("");
				boolean success = userService.addUser(user);
				return packSaveInfo(success);
			} catch (Exception e) {
				e.printStackTrace();
				return warnException(e);
			}
		} else {
			return packInfo(false, "无权操作，保存");
		}
	}

}
